package com.licheedev.demo.utils;

import android.util.Log;

import com.firefly.api.serialport.SerialPort;
import com.firefly.api.serialport.SerialPort.Callback;
import com.firefly.api.serialport.SerialPortFinder;

import java.io.File;
import java.io.IOException;

public class SeriseUtils {

    static SerialPort mSerialPort;
    public static boolean openSerialPort(String path, int baudrate, final SerialCallBack callBack)
    {
        try {
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
            mSerialPort.setCallback(new SerialPort.Callback() {
                @Override
                public void onDataReceived(byte[] buffer, int size) {
                    // TODO Auto-generated method stub
                    String result = new String(buffer, 0, size);
                    callBack.msgCome(result);

                    Log.d("Serise", "onDataReceived:"+result);
                }
            });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("Serise", "open serialport("+path +") error:"+e.toString());
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("Serise", "open serialport("+path +") error:"+e.toString());
            return false;
        }
        return true;
    }

    public static void closeSerialPort() {
        if(mSerialPort!=null){
            mSerialPort.closeSerialPort();
        }
    }
}
